package com.weng.platform.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import com.weng.framework.dao.mybatis.service.BaseServiceImpl;
import com.weng.platform.platform.service.IColumnService;
import com.weng.platform.resource.entity.Resource;
import com.weng.platform.resource.mapper.ResourceMapper;
import com.weng.platform.resource.service.IResourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;


/**
 * 资源信息 服务实现类
 *
 * @author weng
 * @date 2021-03-01 16:29:08
 *
 */ 
@Slf4j
@Service
public class ResourceServiceImpl extends BaseServiceImpl<ResourceMapper, Resource> implements IResourceService {
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private IColumnService columnService;



	/**
	 * @return
	 */
	@Override
	public void incVisitCount(String id, Integer count)  {
		Resource resource =resourceMapper.selectById(id);
		if(resource == null){
			log.error("Resource is no exists for id:{}" ,id);
			return;
		}
		resource.setVisitCount(resource.getVisitCount() + count);
		resourceMapper.updateById(resource);
	}
	/**
	 * 分页查询资源信息
	 * @return
	 */
	@Override
	public IPage<Resource> list(Integer pageNo,Integer pageSize, String ownerId, Boolean isQueryChild, String columnId, String name) {
		QueryWrapper<Resource> qw = new QueryWrapper<>();
		if(isQueryChild!= null && isQueryChild && StringUtils.isNotEmpty(columnId)){
			List<String> childColumnIds = columnService.getAllChildIds(columnId);
			qw.in("column_id", childColumnIds);
		}else{
			qw.eq("column_id",columnId);
		}
		if(StringUtils.isNotEmpty(name)){
			qw.like("name", "%"+name +"%");
		}
		qw.eq("owner_id",ownerId);
		qw.orderByDesc("update_time");
		IPage<Resource> page = new PageModel<>(pageNo,pageSize);
		return resourceMapper.selectPage(page,qw);
	}


	/**
	 * 获取单个资源信息
	 * @param id
	 * @return
	 */
	@Override
	public Resource getById(Serializable id) {
		return super.getById(id);
	}

	/**
	 * 新增单个资源信息
	 * @param resource
	 * @return
	 */
	@Override
	public Resource add(Resource resource)  {
		
		resourceMapper.insert(resource);
		return resource;
	}

	/**
	 * 更新单个资源信息
	 * @param resource
	 * @return
	 * @
	 */
	@Override
	public int update(Resource resource)  {
		
		return resourceMapper.updateById(resource);

	}


	@Override
	public ResponseData removeByIds(String ids) {
		String[] resourceIds = ids.split(",");
		boolean flag = this.removeByIds(Arrays.asList(resourceIds));
		if (flag) {
			return ResponseData.success();
		} else {
			return ResponseData.success();
		}
	}

}
